<template>
  <div class="right-content">
    <div class="connection-header">
      <div>Select Connection:</div>
      <div class="connection-actions">
        <a-button type="text" size="small" @click="showAddDialog">
          <icon-plus />
          New Connection
        </a-button>
      </div>
    </div>
    
    <div class="connection-list">
      <div 
        v-for="connection in connections" 
        :key="connection.id"
        class="connection-item"
        :class="{ active: selectedConnection === connection.name }"
        @click="selectConnection(connection)"
      >
        <span>{{ connection.name }}</span>
        <div class="connection-item-actions">
          <a-button type="text" size="mini" @click.stop="copyConnection(connection)"><icon-copy /></a-button>
          <a-button type="text" size="mini" @click.stop="deleteConnection(connection)"><icon-delete /></a-button>
          <a-button type="text" size="mini" @click.stop="editConnection(connection)"><icon-edit /></a-button>
        </div>
      </div>
      
      <div v-if="connections.length === 0" class="connection-empty">
        No connections found
      </div>
    </div>
    <div class="pagination-container">
      <a-pagination 
        v-model:current="currentPage" 
        :page-size="pageSize" 
        :total="totalConnections" 
        @change="loadConnections"
      />
    </div>
    
  </div>

  <!-- 添加连接对话框 -->
  <a-modal v-model:visible="addDialogVisible" title="New Connection" @ok="handleAddOk" @cancel="addDialogVisible = false">
    <a-form :model="connectionForm" ref="addFormRef">
      <a-form-item field="name" label="Name" :rules="[{ required: true, message: 'Please input connection name' }]">
        <a-input v-model="connectionForm.name" placeholder="Connection name" />
      </a-form-item>
      <a-form-item field="host" label="Host" :rules="[{ required: true, message: 'Please input host' }]">
        <a-input v-model="connectionForm.host" placeholder="Host address" />
      </a-form-item>

      <a-form-item field="username" label="Username">
        <a-input v-model="connectionForm.username" placeholder="Username" />
      </a-form-item>
      <a-form-item field="password" label="Password">
        <a-input-password v-model="connectionForm.password" placeholder="Password" />
      </a-form-item>
      <a-form-item field="group" label="Group">
        <a-input v-model="connectionForm.group" placeholder="Connection group" />
      </a-form-item>
      <a-form-item field="secret" label="Secret">
        <a-input v-model="connectionForm.secret" placeholder="Connection secret" />
      </a-form-item>
      <a-form-item field="insecrue_skip_verify" label="Insecure Skip Verify">
        <a-switch v-model="connectionForm.insecrue_skip_verify" />
      </a-form-item>
      <a-form-item field="no_dtls" label="No DTLS">
        <a-switch v-model="connectionForm.no_dtls" />
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 编辑连接对话框 -->
  <a-modal v-model:visible="editDialogVisible" title="Edit Connection" @ok="handleEditOk" @cancel="editDialogVisible = false">
    <a-form :model="connectionForm" ref="editFormRef">
      <a-form-item field="name" label="Name" :rules="[{ required: true, message: 'Please input connection name' }]">
        <a-input v-model="connectionForm.name" placeholder="Connection name" />
      </a-form-item>
      <a-form-item field="host" label="Host" :rules="[{ required: true, message: 'Please input host' }]">
        <a-input v-model="connectionForm.host" placeholder="Host address" />
      </a-form-item>
      <a-form-item field="username" label="Username">
        <a-input v-model="connectionForm.username" placeholder="Username" />
      </a-form-item>
      <a-form-item field="password" label="Password">
        <a-input-password v-model="connectionForm.password" placeholder="Password" />
      </a-form-item>
      <a-form-item field="group" label="Group">
        <a-input v-model="connectionForm.group" placeholder="Connection group" />
      </a-form-item>
      <a-form-item field="secret" label="Secret">
        <a-input v-model="connectionForm.secret" placeholder="Connection secret" />
      </a-form-item>
      <a-form-item field="insecrue_skip_verify" label="Insecure Skip Verify">
        <a-switch v-model="connectionForm.insecrue_skip_verify" />
      </a-form-item>
      <a-form-item field="no_dtls" label="No DTLS">
        <a-switch v-model="connectionForm.no_dtls" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, onMounted, defineModel } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { IconPlus, IconCopy, IconDelete, IconEdit } from '@arco-design/web-vue/es/icon';
import { App } from '../../../bindings/slapp3/backend';
import { Profile } from '../../../bindings/slapp3/backend/application/domain';

const selectConnectionId = defineModel<number|undefined>('selectedConnectionId', {
  default: undefined,
});
const selectedConnection = ref('');
const connections = ref<Profile[]>([]);
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);

const connectionForm = ref<Profile>({
  id: 0,
  name: '',
  host: '',
  username: '',
  password: '',
  group: '',
  secret: '',
  insecrue_skip_verify: false,
  no_dtls: true,
  version: '',
});
const editingConnectionId = ref<number | string>('');
const addFormRef = ref();
const editFormRef = ref();

// 分页相关变量
const pageSize = ref(5); // 每页显示的连接数
const currentPage = ref(1); // 当前页码
const totalConnections = ref(0); // 总连接数



// 加载连接列表
const loadConnections = async () => {
  try {
    const result = await App.ListConnects(currentPage.value, pageSize.value);
    console.log('Loaded connections:', result);
    connections.value = result.profiles || [];
    
    totalConnections.value = result.total || 0;
    
  } catch (error) {
    Message.error('Failed to load connections');
    console.error(error);
  }
};



// 选择连接
const selectConnection = (connection: Profile) => {
  selectedConnection.value = connection.name;
  // 可以在这里添加加载连接详情的代码
  selectConnectionId.value = connection.id;
};

// 显示添加对话框
const showAddDialog = () => {
  connectionForm.value = {
    id: 0,
    name: '',
    host: '',
    username: '',
    password: '',
    // 确保初始化所有必要字段
    group: '',
    secret: '',
    insecrue_skip_verify: false,
    no_dtls: true,
    version:''
  };
  
  addDialogVisible.value = true;
};

// 处理添加确认
const handleAddOk = async () => {
  try {
    await addFormRef.value.validate();
    await App.CreateConnect(connectionForm.value);
    addDialogVisible.value = false;
    Message.success('Connection added successfully');
    await loadConnections();
  } catch (error) {
    Message.error('Failed to add connection');
    console.error(error);
  }
};

// 复制连接
const copyConnection = async (connection: Profile) => {
  try {
    const copyName = `${connection.name} (copy)`;
    const newConnection = { ...connection, id: 0, name: copyName }; // Reset ID for new connection
    await App.CreateConnect(newConnection);
    Message.success('Connection copied successfully');
    await loadConnections();
  } catch (error) {
    Message.error('Failed to copy connection');
    console.error(error);
  }
};

// 删除连接
const deleteConnection = async (connection: Profile) => {
  Modal.confirm({
    title: 'Confirm Deletion',
    content: `Are you sure you want to delete connection "${connection.name}"?`,
    onOk: async () => {
      try {
        await App.DeleteConnect(connection.id);
        Message.success('Connection deleted successfully');
        await loadConnections();
        
        if (selectedConnection.value === connection.name) {
          selectedConnection.value = '';
        }
      } catch (error) {
        Message.error('Failed to delete connection');
        console.error(error);
      }
    }
  });
};

// 编辑连接
const editConnection = (connection: Profile) => {
  connectionForm.value = { ...connection };
  editingConnectionId.value = connection.id;
  editDialogVisible.value = true;
};

// 处理编辑确认
const handleEditOk = async () => {
  try {
      await editFormRef.value.validate();
    await App.UpdateConnect(connectionForm.value);
    editDialogVisible.value = false;
    Message.success('Connection updated successfully');
    await loadConnections();
    // 如果编辑的是当前选中的连接，更新选中值
    if (selectedConnection.value === connectionForm.value.name) {
      selectedConnection.value = connectionForm.value.name;
    }
  } catch (error) {
    Message.error('Failed to update connection');
    console.error(error);
  }
};

// 初始化加载
onMounted(async () => {
  await loadConnections();
});
</script>

<style lang="less" scoped>
.right-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.connection-header {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e9e9e9;
}

.connection-actions {
  display: flex;
  gap: 8px;
}

.connection-list {
  flex: 1;
  overflow-y: auto;
}

.connection-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  
  &:hover {
    background-color: #f5f5f5;
  }
  
  &.active {
    background-color: #e6f7ff;
  }
}

.connection-item-actions {
  display: flex;
  gap: 4px;
}

.connection-empty {
  padding: 20px;
  text-align: center;
  color: #999;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 10px;
  border-top: 1px solid #f0f0f0;
}
</style>